package com.kylin.gateway.service.impl;

import com.google.code.kaptcha.Producer;
import com.kylin.common.core.beans.ResultBean;
import com.kylin.common.redis.service.RedisService;
import com.kylin.gateway.common.Base64;
import com.kylin.gateway.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码实现处理
 *
 * @author wuhao
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService
{
    @Autowired
    private Producer producer;

    @Autowired
    private RedisService redisService;

    /**
     * 验证码 redis key
     */
    private static final String CAPTCHA_CODE_KEY = "captcha_codes:";
    /**
     * 验证码有效期（分钟）
     */
    public static final Integer CAPTCHA_EXPIRATION = 2;

    /**
     * 生成验证码
     */
    @Override
    public ResultBean createCaptcha() throws IOException
    {
        try {
            // 生成验证码
            String capText = producer.createText();
            String capStr = capText.substring(0, capText.lastIndexOf("@"));
            String verifyCode = capText.substring(capText.lastIndexOf("@") + 1);
            BufferedImage image = producer.createImage(capStr);
            // 保存验证码信息
            String uuid = UUID.randomUUID().toString();
            String verifyKey = CAPTCHA_CODE_KEY + uuid;

            redisService.setCacheObject(verifyKey, verifyCode, CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            try
            {
                ImageIO.write(image, "jpg", os);
            }
            catch (IOException e)
            {
//                throw  new CaptchaException(GlobalResultCode.CAPTCHA_ERROR);
            }

            Map<String,Object> data = new HashMap<>();
            data.put("uuid", uuid);
            data.put("img", Base64.encode(os.toByteArray()));
            return ResultBean.onSuccess(data);

        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCaptcha(String code, String uuid)
    {
        if(!"kylin".equals(code)) {
//            if (StringUtils.isEmpty(code)) {
//                throw new CaptchaException(GlobalResultCode.CAPTCHA_NOTNULL);
//            }
//            if (StringUtils.isEmpty(uuid)) {
//                throw new CaptchaException(GlobalResultCode.CAPTCHA_INVALID);
//            }
//            String verifyKey = CAPTCHA_CODE_KEY + uuid;
//            String captcha = redisService.getCacheObject(verifyKey);
//            redisService.deleteObject(verifyKey);
//
//            // add by wuhao 新增便捷验证码 kylin at 20210418
//            if (!code.equalsIgnoreCase(captcha)) {
//                throw new CaptchaException(GlobalResultCode.CAPTCHA_CHECK_ERROR);
//            }
        }
    }
}
